package cn.com.wxd.dao.website;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import org.springframework.jdbc.core.JdbcTemplate;

import cn.com.wxd.dao.HibernateDao;
import cn.com.wxd.entity.website.ArticleInfo;
import cn.com.wxd.entity.website.CatalogInfo;
import cn.com.wxd.common.CharUtil;
import cn.com.wxd.util.dao.JdbcUtil;

/**
 * Title:CatalogDaoImpl.java
 * Description:cn.com.wxd.dao.catalog
 * 
 * Company: wxd网站系统
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2015年10月22日 下午5:24:38
 *
 * @author WangXuDong
 * @version 1.0
 */
public class CatalogDaoImpl extends HibernateDao implements CatalogDao {
	private static final Logger log = LoggerFactory.getLogger(ArticleDaoImpl.class);
	@Override
	/**
	 * 根据参数获取栏目，参数为NULL则获取到所有的栏目
	 * @param param 相关查询条件参数
	 * @return 返回栏目列表
	 */
	public List<CatalogInfo> selectAllCatalog(Map<String,String> param) {
		Session session = this.currentSession();
		List<CatalogInfo> catalogInfo;
		Criteria cri = session.createCriteria(CatalogInfo.class);
		if(param!=null){
			for (String key : param.keySet()) { 
				cri = cri.add(Restrictions.eq(key, param.get(key)));
			}
		}
		catalogInfo = cri.addOrder(Order.desc("orderId")).list();
		return catalogInfo;
	}
	@Override
	/**
	 * 根据id获取栏目
	 */
	public CatalogInfo getCatalogById(int id) {
		Session session = this.currentSession();
		return (CatalogInfo)session.get(CatalogInfo.class, id);
	}

	@Override
	@Deprecated
	public List<CatalogInfo> selectAllCatalogOfJdbc(Map<String,String> param){
		String sql = "SELECT * FROM CATALOG WHERE 1=1";
		if(param!=null){
			for (String key : param.keySet()) {
					sql += " AND "+key+"='"+param.get(key)+"'";
			}
		}
		List<Map<String,Object>> list;
		JdbcTemplate jdbcTemp = JdbcUtil.getJdbcTemplate();
		list = jdbcTemp.queryForList(sql);
		Iterator<Map<String, Object>> iter = list.iterator();
		List<CatalogInfo> catalist = new ArrayList<>();
		while(iter.hasNext()){
			Map catamap = iter.next();
			CatalogInfo ci = new CatalogInfo();
			ci.setId(Integer.valueOf(catamap.get("id").toString()));
			ci.setIsShow((String)catamap.get("isShow"));
			ci.setName((String)catamap.get("name"));
			Object parId = catamap.get("parentId");
			if(parId==null){
				ci.setParentId(null);
			}else{
				ci.setParentId(Integer.parseInt(parId.toString()));
			}			
			ci.setRemark((String)catamap.get("remark"));
			ci.setShowType((String)catamap.get("showType"));
			ci.setType((String)catamap.get("type"));
			catalist.add(ci);
		}
		return catalist;
	}
	@Override
	/**
	 * 获取根栏目
	 */
	public List<CatalogInfo> selectRootCatalog() {
		Session session = this.currentSession();
		List<CatalogInfo> cis;
		String hql = "from CatalogInfo c where parentId='' or parentId is null or parentId = 0 order by orderId desc";
		cis = session.createQuery(hql).list();
		//cis = session.createCriteria(CatalogInfo.class).add(Restrictions.or(Restrictions.isEmpty("parentId"),
		// Property.forName("parentId").isNull())).list();
		return cis;
	}
	@Override
	/**
	 * 根据栏目号查子栏目列表
	 */
	public List<CatalogInfo> selectSubCatalogById(int id) {
		Session session = this.currentSession();
		List<CatalogInfo> cis;
		cis = session.createCriteria(CatalogInfo.class)
				.add(Restrictions.eq("parentId", id))
				.addOrder(Order.desc("orderId"))
				.list();
		return cis;
	}
	@Override
	/**
	 * 保存栏目
	 */
	public boolean insertCatalog(CatalogInfo catalogInfo) {
		Session session = this.currentSession();
		try {
			session.saveOrUpdate(catalogInfo);
			return true;
		} catch (Exception e) {
			log.error("",e);
			return false;
		}
	}
	@Override
	/**
	 * 删除栏目
	 */
	public boolean deleteCatalog(int id) {
		Session session = this.currentSession();
		try {
			 //获取并删除栏目
			session.delete(session.get(CatalogInfo.class, id));
			return true;
		} catch (Exception e) {
			log.error("",e);
			return false;
		}
	}

	@Override
	public long selectArtCountByCaid(int caid) {
		Session session = currentSession();
		Criteria c2 = session.createCriteria(ArticleInfo.class);
		c2.add(Restrictions.eq("caId", caid));
		int num = CharUtil.stringParsInt(c2.setProjection(Projections.rowCount()).uniqueResult().toString());
		return num;
	}

	@Override
	/**
	 * 查询子栏目数量
	 */
	public int selectSubCatalogCount(int id) {
		Session session = this.currentSession();
		int count = -1;
		try {
			count = CharUtil.stringParsInt(session.createCriteria(CatalogInfo.class)
					.add(Restrictions.eq("parentId", id))
					.setProjection(Projections.rowCount())
					.uniqueResult()
					.toString());
			
		} catch (Exception e) {
			log.error("",e);
		}
		return count;
	}

	@Override
	/**
	 * 根据栏目标识号查栏目
	 * @param cataCode 栏目标识号
	 * @return 栏目对象
	 */
	public CatalogInfo selectCatalogBycode(String cataCode) {
		Session session = this.currentSession();
		CatalogInfo cataloginfo;
		cataloginfo = (CatalogInfo)session.createCriteria(CatalogInfo.class)
				.add(Restrictions.eq("cataCode", cataCode))
				.uniqueResult();		
		return cataloginfo;
	}
	@Override
	/**
	 * 获取目前最大的文章排序号
	 */
	public int selectMaxOrderId() {
		Session session = currentSession();
		Criteria c = session.createCriteria(CatalogInfo.class);
		c.setProjection(Projections.max("orderId"));
		Integer in = (Integer) c.uniqueResult();
		if(in==null){
			return 0;
		}
		return in;
	}
	@Override
	/**
	 * 文章排序
	 * @param newOrdId 新的排序号
	 * @param oldOrdId 旧的排序号
	 * @return 是否成功
	 */
	public boolean updateCatalogOrder(int newOrdId, int oldOrdId) {
		Session session = currentSession();
		try {
			Criteria c = session.createCriteria(CatalogInfo.class);
			Criteria c2 = session.createCriteria(CatalogInfo.class);
			CatalogInfo oldai = (CatalogInfo)(c.add(Restrictions.eq("orderId", oldOrdId)).uniqueResult());
			CatalogInfo newai = (CatalogInfo)(c2.add(Restrictions.eq("orderId", newOrdId)).uniqueResult());
			oldai.setOrderId(newOrdId);
			newai.setOrderId(oldOrdId);
			
			session.update(oldai);    //交换orderId
			session.update(newai);
		} catch (Exception e) {
			log.error("排序异常："+e.getMessage());
			return false;
		}
		return true;
	}

}
